import { Button, Form, Input, message } from 'antd'
import { useState } from 'react'
import { Link, useNavigate } from 'react-router'
import { getLoginUser, userLogin } from '@/apis'
import { useUserStore } from '@/stores'

export const Login = () => {
  const navigate = useNavigate()
  const [formState, setFormState] = useState({
    userAccount: '',
    userPassword: '',
  })

  const setUser = useUserStore((state) => state.setUser)
  const handleSubmit = async (values: API.UserLoginRequest) => {
    const res = await userLogin(values)
    if (res.data.code === 0 && res.data.data) {
      const res = await getLoginUser()

      if (res.data.code === 0 && res.data.data) {
        setUser(res.data.data)
      }
      message.success('登录成功！')
      navigate('/', { replace: true })
    } else {
      message.error('登录失败，' + res.data.message)
    }
  }

  return (
    <div className="bg-white m-[24px_auto] max-w-[720px] p-[24px]">
      <h2 className="text-center mb-[16px]">用户登录</h2>
      <Form
        name="basic"
        autoComplete="off"
        onFinish={handleSubmit}
        initialValues={formState}
        style={{ maxWidth: 400, margin: '0 auto' }}
      >
        <Form.Item name="userAccount" rules={[{ required: true, message: '请输入账号' }]}>
          <Input
            placeholder="请输入账号"
            value={formState.userAccount}
            onChange={(e) => setFormState({ ...formState, userAccount: e.target.value })}
          />
        </Form.Item>

        <Form.Item
          name="userPassword"
          rules={[
            { required: true, message: '请输入密码' },
            { min: 8, message: '密码长度不能小于 8 位' },
          ]}
        >
          <Input.Password
            placeholder="请输入密码"
            value={formState.userPassword}
            onChange={(e) => setFormState({ ...formState, userPassword: e.target.value })}
          />
        </Form.Item>

        <div className="text-center text-gray-600">
          没有账号{' '}
          <Link to="/user/register" className="text-blue-500 hover:text-blue-700">
            去注册
          </Link>
        </div>

        <Form.Item>
          <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
